<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/css/bootstrap.css"
      rel="stylesheet"
    />
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.2/js/bootstrap.js"></script>
    <style>
      /* body {
        background-color: rgba(0, 0, 0, 0.2);
      }
      #modal {
        position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        z-index: 999;
        padding: 4em;
        background-color: white;
        display: none;
      } */
    </style>
  </head>
  <body>
    <!-- 按钮打开弹框 -->
    <!-- 添加和修改都是差不多的操作 -->
    <!-- data-bs-toggle 这个按钮，要用来打开弹框 -->
    <!-- data-bs-target 要被打开的弹框的 id -->
    <button
      type="button"
      class="btn btn-primary"
      data-bs-toggle="modal"
      data-bs-target="#createModal"
    >
      添加
    </button>

    <!-- 弹框 -->
    <div
      class="modal fade"
      id="createModal"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">添加图书</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <form id="createForm">
              <div>
                <label for="bookname">图书名</label>
                <input
                  placeholder="请输入图书名"
                  id="bookname"
                  name="bookname"
                />
              </div>
              <div>
                <label for="writer">作者</label>
                <input placeholder="请输入作者名字" id="writer" name="writer" />
              </div>
              <div>
                <label for="publisher">出版社</label>
                <input
                  placeholder="请输入出版社名称"
                  id="publisher"
                  name="publisher"
                />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              关闭
            </button>
            <button
              type="button"
              class="btn btn-primary"
              data-bs-dismiss="modal"
              id="createBtn"
            >
              保存
            </button>
          </div>
        </div>
      </div>
    </div>

    <button
      type="button"
      class="btn btn-primary"
      data-bs-toggle="modal"
      data-bs-target="#updateModal"
    >
      修改
    </button>

    <!-- 修改 -->
    <div
      class="modal fade"
      id="updateModal"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">修改图书</h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <form id="updateForm">
              <div>
                <label for="bookname">图书名</label>
                <input
                  placeholder="请输入图书名"
                  id="bookname"
                  name="bookname"
                />
              </div>
              <div>
                <label for="writer">作者</label>
                <input placeholder="请输入作者名字" id="writer" name="writer" />
              </div>
              <div>
                <label for="publisher">出版社</label>
                <input
                  placeholder="请输入出版社名称"
                  id="publisher"
                  name="publisher"
                />
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-bs-dismiss="modal"
            >
              关闭
            </button>
            <button
              type="button"
              class="btn btn-primary"
              data-bs-dismiss="modal"
              id="updateBtn"
            >
              保存
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 点击按钮，出现一个弹框 -->
    <!-- 点击弹框里的按钮，弹框消失 -->
    <!-- 弹框显示在全部页面之上中间 -->

    <!-- 图书列表 的 表格 -->
    <table id="data"></table>
  </body>
  <script>
    // 查 get 增 post 删 delete  改 put
    // get/delete 只是 delete 要加上 method = delete'
    // put/post
    // 难的是修改，因为你面对的是很多条数据 你需要把每一条数据回填到修改的弹框上

    // 查
    fetch("http://192.168.22.29:4000/books", { method: "GET" })
      .then((res) => res.json())
      .then((res) => {
        // 获取的结果，展示在 table 中
        const list = res.data;
        // list 用 map 转换成  `<tr><td> </td></tr>`
        console.log(res);
        const tableHeader = `<tr>
        <th>Id</th>
        <th>书名</th>
        <th>作者</th>
        <th>出版社</th>
        <th>操作</th>
      </tr>`;
        const listContent =
          tableHeader +
          // map 方法
          // 数据有很多条
          // 考虑一个数据或者多个数据的问题
          list
            .map(
              // 表格里面的每一项
              // el element 元素 数组里面的每一项
              (el) => `<tr>
            <td>${el.id}</td>
            <td>${el.bookname}</td>
            <td>${el.author}</td>
            <td>${el.publisher}</td>
            <td>
                <button data-id="${el.id}" id="delete">删除</button>
                <button data-id="${el.id}" data-bookname="${el.bookname}" data-author="${el.author}" data-publisher = "${el.publisher}" class="update" data-bs-toggle="modal" data-bs-target="#updateModal">修改</button>
            </td>
            </tr>`
            )
            .join("");
        document.querySelector("#data").innerHTML = listContent;

        const deleteBtns = document.querySelectorAll(".delete");
        console.log(deleteBtns);
        deleteBtns.forEach((el) => {
          el.onclick = (e) => {
            // e.target.dataset
            const id = e.target.getAttribute("data-id");
            console.log(id);
            fetch("http://192.168.22.29:4000/books?id=" + id, {
              method: "delete",
            })
              .then((res) => res.json())
              .then((res) => {
                console.log(res);
              });
          };
        });

        // 1. 因为渲染数据时，数据不止一条
        // 2. 所以需要监听的按钮，不止一个
        // 3. dataset： 只要标签上有 data-xxx ，我们就可以通过 node.dataset 拿到绑在标签上的数据
        // 4. 监听，也需要针对一个 querySelectAll 获取的节点列表，它也不止一个
        // 5. 在 nodeList（updateBtns）中 forEach，对每一个节点进行监听
        // 6. 用 dataset 获取数据
        // 7. 将数据回填到 updateform
        // 8. formData 取值[]
        // 9. put 请求发送
        const updateBtns = document.querySelectorAll(".update");
        updateBtns.forEach((el) => {
          el.onclick = () => {
            console.log(el.dataset);
            const updateForm = document.querySelector("#updateForm");
            // 回填进表单
            updateForm.querySelector('[name="bookname"]').value =
              el.dataset.bookname;
            updateForm.querySelector('[name="publisher"]').value =
              el.dataset.publisher;
            updateForm.querySelector('[name="writer"]').value =
              el.dataset.author;
            document.querySelector("#updateBtn").onclick = () => {
              const formData = new FormData(updateForm);
              fetch("http://192.168.22.29:4000/books", {
                method: "put",
                headers: {
                  "content-type": "application/json",
                },
                body: JSON.stringify({
                  id: el.dataset.id,
                  author: formData.get("writer"),
                  publisher: formData.get("publisher"),
                  bookname: formData.get("bookname"),
                }),
              }) //解析返回的数据
                .then((result) => result.json())
                .then((res) => {
                  console.log(res);
                });
            };
          };
        });

        // const updateBtns = document.querySelectorAll(".updateBtn");
        // console.log(updateBtns);
        // updateBtns.forEach((el) => {
        //   el.onclick = (e) => {
        //     const id = e.target.getAttribute("data-id");
        //     const updateForm = document.querySelector("#updateForm-" + id);
        //     const formData = new FormData(updateForm);
        //     fetch("http://192.168.22.29:4000/books", {
        //       method: "put",
        //       headers: {
        //         "content-type": "application/json",
        //       },
        //       body: JSON.stringify({
        //         id,
        //         author: formData.get("writer"),
        //         publisher: formData.get("publisher"),
        //         bookname: formData.get("bookname"),
        //       }),
        //     })
        //       .then((res) => res.json())
        //       .then((res) => {
        //         console.log(res);
        //       });
        //   };
        // });
      });
    const updateBtns = document.querySelectorAll(".update");
    console.log("外面的 updateBtns", updateBtns);
    updateBtns.forEach((el) => {
      el.onclick = () => {
        console.log(el.dataset);
        update;
      };
    });

    // 增
    const createBtn = document.querySelector("#createBtn");
    const createForm = document.querySelector("#createForm");

    createBtn.onclick = () => {
      const formData = new FormData(createForm);
      const bookname = formData.get("bookname");
      const writer = formData.get("writer");
      const publisher = formData.get("publisher");
      console.log(bookname, writer, publisher);
      fetch("http://192.168.22.29:4000/books", {
        method: "POST",
        headers: {
          "content-type": "application/json",
        },
        body: JSON.stringify({
          bookname,
          author: writer,
          publisher,
        }),
      })
        .then((res) => res.json())
        .then((res) => {
          console.log(res);
        });
    };
  </script>
</html>
